﻿/**
 *    Copyright 2012 Yohan Courbe
 *
 *  Licensed under the Apache License, Version 2.0 (the "License") 
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *      
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;

namespace NetworkAnalyzer.Engines.Graphics.HttpHits
{
    internal static class GraphicsHttpHits
    {
        public static List<HttpHit> HttpHits;
        public static bool Enabled { get; private set; }
        public static readonly object Locker = new object();

        private static readonly Timer ActivityTimer = new Timer { AutoReset = true, Enabled = true, Interval = 100 };

        public static void StartSystem()
        {
            Console.WriteLine("Start HttpHits");

            HttpHits = new List<HttpHit>();
            ActivityTimer.Elapsed += DescreaseActivity;
            ActivityTimer.Start();
            Enabled = true;
        }

        public static void StopSystem()
        {
            Console.WriteLine("Stop HttpHits");

            ActivityTimer.Stop();
            Enabled = false;
        }

        private static void DescreaseActivity(Object sender, ElapsedEventArgs e)
        {
            lock (Locker)
            {
                foreach (var httpHit in HttpHits.Where<HttpHit>(httpHit => httpHit.Activity > 1))
                {
                    httpHit.DecreaseActivity();
                }
            }
        }

        public static void AddHit(string domain)
        {
            if (!Enabled) return;

            lock (Locker)
            {
                foreach (var httpHit in HttpHits.Where<HttpHit>(httpHit => httpHit.Domain.Equals(domain)))
                {
                    httpHit.IncreaseActivity();
                    return;
                }

                HttpHits.Add(new HttpHit(domain));
            }
        }
    }
}
